package com.zhaokuner.springcloudconfigserver.zk;

import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * <p>
 * Description:log显示
 * <p>
 * Copyright: 2018-现在 北京掌通未来科技有限公司
 * <p>
 *
 * @author 赵希坤 zhaoxikun
 * @date 2020/8/1 14:50
 */
@Controller
@RequestMapping("/log")
public class ZkLogCtrl {
    @Autowired
    private CuratorClient client;
    @Value("${spring.cloud.config.zkChangeLog.enabled}")
    private Boolean zkChangeLogEnabled;


    @RequestMapping
    public String log(ModelMap model) {
        model.put("root", client.getZkChangeLogPrefix());
        if (!Boolean.TRUE.equals(zkChangeLogEnabled)) {
            model.put("error", "日志记录未开启");
            return "branch";
        }
        try {
            model.put("list", client.getRootChildren());
        } catch (Exception e) {
            CharArrayWriter writer = new CharArrayWriter();
            e.printStackTrace(new PrintWriter(writer));
            model.put("error", writer.toString());
        }
        return "branch";
    }

    @RequestMapping("{name}")
    public String branch(ModelMap model, @PathVariable String name) {
        model.put("branch", name);
        try {
            LinkedHashMap<String, String> map = client.getBranchChildren(name);
            LinkedHashMap<String, HashMap<String, String>> mapList = new LinkedHashMap<>(8);
            map.forEach((k, v) -> {
                HashMap<String, String> m = new HashMap<>(8);
                JSONArray array = JSONArray.parseArray(v);
                m.put("time", array.getString(0));
                m.put("commitId", array.getString(1));
                m.put("message", array.getString(2));
                mapList.put(k, m);
            });
            model.put("map", mapList);
        } catch (Exception e) {
            e.printStackTrace();
            CharArrayWriter writer = new CharArrayWriter();
            e.printStackTrace(new PrintWriter(writer));
            model.put("error", writer.toString());
        }
        return "file";
    }
}
